
import { Button, Tabs, Input, Form, Select, Badge } from 'antd';
import styles from './style.less';
import { history } from 'umi';
import { useEffect, useState } from 'react';
import { ThunderboltOutlined } from '@ant-design/icons'
import { saveApi, getById, updateApi } from '@/services/doc/api'
const { Option } = Select;
import { RichTextEdit } from '@/components/RichText'
import ApiParamEditTable, { ComplexParamEditTable } from '../ApiParamEditTable'
import ApiErrorCodeSelect from '../ApiErrorCode/ApiErrorCodeSelect'
import IdUtils from '@/utils/IdUtils'
import DirSelect from '@/components/doc/DirMenu/DirSelect'
const ApiEdit = (props) => {
    const {
        projectId,
        projectPermission,
        routeParam,
        currentDocData,
        dirTreeData
    } = props;

    const [form] = Form.useForm()
    const [paramData, setParamData] = useState({});
    const [formData, setFormData] = useState();
    const [saveLoading, setSaveLoading] = useState(false)
    useEffect(() => {
        if (formData) {
            form.resetFields();
        }
    }, [formData])

    useEffect(() => {
        console.log(currentDocData)
        if (currentDocData) {
            if (currentDocData.apiId) {
                getById(projectId, currentDocData.apiId).then((result) => {
                    let apiData = result?.data;
                    setFormData({
                        ...apiData
                    })
                    setParamData({
                        headers: apiData.headers,
                        requestBody: apiData.request.body,
                        queryParams: apiData.request.queryParams,
                        pathParams: { fields: apiData.request.pathParams },
                        responseHeaders: apiData.response.headers,
                        responseBody: apiData.response.body,
                    })
                })
                // 通过接口获取api信息
            } else {
                let dir = currentDocData.dir
                // 新增
                setFormData({
                    protocol: "HTTP",
                    method: "GET",
                    dirId: dir?.id
                })

            }
        } else {
            setFormData({
                protocol: "HTTP",
                method: "GET"
            })
        }
    }, [currentDocData])

    const onSaveApi = async () => {
        const apiData = await form.validateFields();
        setSaveLoading(true)
        // console.log("onSaveApi", apiData, paramData)
        let newApiData = {
            ...apiData,
            headers: paramData.headers,
            request: {
                body: paramData.requestBody || {},
                queryParams: paramData.queryParams || {},
                pathParams: paramData.pathParams?.fields || []
            },
            response: {
                headers: paramData.responseHeaders || {},
                body: paramData.responseBody || {},
                errorCodeList: apiData.response?.errorCodeList || [],
            }
        }
        if (currentDocData?.apiId) {
            updateApi(projectId, currentDocData?.apiId, newApiData).then((result) => {
                setSaveLoading(false)
                history.push(`/projects/${projectId}/api/${currentDocData?.apiId}`)
            })
        } else {
            saveApi(projectId, newApiData).then((result) => {
                setSaveLoading(false)
                history.push(`/projects/${projectId}/api/${result?.data.id}`)
            })
        }
    }

    const onQuickSaveApi = () => {

    }

    const onParamChange = (paramName, values) => {
        paramData[paramName] = values;
    }

    const onParamTabChange = () => {
        setParamData({
            ...paramData
        })
    }

    const onValuesChange = (values) => {
        // console.log("onValuesChange", values)
        if (values.url) {
            let regex = /{[a-zA-Z0-9]+}/ig;
            let pathParams = values.url.match(regex);
            let oldParams = paramData?.pathParams?.fields || []
            let ifModify = [false];
            if (pathParams && pathParams.length > 0) {
                let newParams = pathParams.map(param => {
                    return param.replace("{", "").replace("}", "")
                }).map((item, index) => {
                    let oldParam = oldParams[index];
                    if (oldParam?.name !== item) {
                        ifModify[0] = true;
                    }
                    if (oldParam) {
                        return {
                            ...oldParam,
                            name: item
                        }
                    }
                    return {
                        name: item,
                        id: IdUtils.uuid(),
                        type: "string",
                        isRequire: true,
                    }
                })
                if (ifModify[0]) {
                    setParamData({
                        ...paramData,
                        pathParams: {
                            fields: newParams
                        }
                    })
                }
            }
        }
    }

    return <div className={styles.apiContext}>
        <div className={styles.header}>
            <div className={styles.route}>
                新增接口
            </div>

            <div className={styles.actions}>
                <Input.Group compact>
                    <Button type="primary" loading={saveLoading} onClick={onSaveApi}>保存</Button>
                    <Button type="primary" loading={saveLoading} onClick={onQuickSaveApi} icon={<ThunderboltOutlined />}></Button>
                </Input.Group>
            </div>

        </div>
        <Form
            form={form}
            initialValues={formData}
            onValuesChange={onValuesChange}
        >
            <Form.Item
                label="目录"
                name={'dirId'}
            >
                <DirSelect dirTree={dirTreeData}></DirSelect>
            </Form.Item>
            <Form.Item
                label="名称"
                name={"name"}
                rules={[{ required: true, message: '请输入名称' }, {
                    type: "string",
                    max: 50,
                    min: 1,
                    message: '名称为3~50个字符'
                }]}
            >
                <Input placeholder="请输入名称" />
            </Form.Item>
            <Form.Item label="接口URL">
                <Input.Group compact>
                    <Form.Item
                        name={'protocol'}
                        noStyle
                        rules={[{
                            required: true,
                            message: '请输入协议'
                        }]}
                    >
                        <Select style={{
                            width: "78px"
                        }} placeholder="协议">
                            <Option value="HTTP">HTTP</Option>
                            <Option value="HTTPS">HTTPS</Option>
                            <Option value="WS">WS</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name={"method"}
                        noStyle
                        rules={[{
                            required: true,
                            message: '请输入请求方式'
                        }]}
                    >
                        <Select style={{
                            width: "96px"
                        }} placeholder="方式">
                            <Option value="GET">GET</Option>
                            <Option value="POST">POST</Option>
                            <Option value="PUT">PUT</Option>
                            <Option value="DELETE">DELETE</Option>
                            <Option value="HEAD">HEAD</Option>
                            <Option value="OPTIONS">OPTIONS</Option>
                            <Option value="PATCH">PATCH</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name={"url"}
                        noStyle
                        rules={[{ required: true, message: '请输入url' }, {
                            type: "string",
                            max: 100,
                            min: 1,
                            message: 'url为3~100个字符'
                        }]}
                    >
                        <Input style={{
                            width: "calc(100% - 180px)"
                        }} placeholder="请输入url" />
                    </Form.Item>
                </Input.Group>
            </Form.Item>
            {paramData?.pathParams && paramData.pathParams.fields.length > 0 && (
                <Form.Item label="路径参数">
                    <ApiParamEditTable hasChildren={false}
                        value={paramData?.pathParams}
                        onChange={(values) => onParamChange("pathParams", values)}
                        enableTypes={["string", "number"]}
                        dragable={false}
                        operation={false}
                        actions={[]}></ApiParamEditTable>
                </Form.Item>
            )}
            <Form.Item label="请求">
                <Tabs type="card" className={styles.request} onChange={onParamTabChange}>
                    <Tabs.TabPane tab={<Badge dot={paramData.headers?.fields && paramData.headers.fields.length > 0}>请求头</Badge>} key="headers">
                        <ApiParamEditTable value={paramData.headers} hasChildren={false}
                            onChange={(values) => onParamChange("headers", values)}
                            actions={["relateModel"]}
                            enableTypes={["string", "number"]}></ApiParamEditTable>
                    </Tabs.TabPane>
                    <Tabs.TabPane tab={<Badge dot={paramData.queryParams?.fields && paramData.queryParams.fields.length > 0}>Query参数</Badge>} key="queryParams" >
                        <ApiParamEditTable value={paramData.queryParams} hasChildren={false} onChange={(values) => onParamChange("queryParams", values)} enableTypes={["string", "number", "array"]} ></ApiParamEditTable>
                    </Tabs.TabPane>
                    <Tabs.TabPane tab={<Badge dot={paramData.requestBody && Object.keys(paramData.requestBody).length > 0}>请求体</Badge>} key="requestBody">
                        <ComplexParamEditTable value={paramData.requestBody} onChange={(values) => onParamChange("requestBody", values)} ></ComplexParamEditTable>
                    </Tabs.TabPane>
                </Tabs>
            </Form.Item>
            <Form.Item label="响应">
                <Tabs type="card" className={styles.response} onChange={onParamTabChange}>
                    <Tabs.TabPane tab={<Badge dot={paramData.responseHeaders?.fields && paramData.responseHeaders.fields.length > 0}>响应头</Badge>} key="responseHeaders">
                        <ApiParamEditTable value={paramData.responseHeaders} hasChildren={false} onChange={(values) => onParamChange("responseHeaders", values)} enableTypes={["string", "number"]}></ApiParamEditTable>
                    </Tabs.TabPane>
                    <Tabs.TabPane tab={<Badge dot={paramData.responseBody && Object.keys(paramData.responseBody).length > 0}>响应体</Badge>} key="responseBody">
                        <ComplexParamEditTable value={paramData.responseBody} onChange={(values) => onParamChange("responseBody", values)}></ComplexParamEditTable>
                    </Tabs.TabPane>
                </Tabs>
            </Form.Item>
            <Form.Item label="错误码" name={["response", "errorCodeList"]}>
                <ApiErrorCodeSelect projectId={projectId}></ApiErrorCodeSelect>
            </Form.Item>
            <Form.Item
                label="描述"
                name={"description"}
            >
                <RichTextEdit showFormButton={false} size="small" />
            </Form.Item>

        </Form>
    </div>
}

export default ApiEdit;